package org.example.ExperimentThree.serverfile;

import java.io.*;
import java.net.Socket;

class FileServerThread extends Thread {
    private final Socket socket;

    public FileServerThread(Socket s) {
        this.socket = s;
    }

    @Override
    public void run() {
        try {
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

            while (true) {
                String command = dis.readUTF();
                if (command.equals("ls")) {
                    sendFileList(dos);
                } else if (command.startsWith("get ")) {
                    String filename = command.substring(4);
                    sendFile(filename, dos);
                } else if (command.startsWith("put ")) {
                    String filename = command.substring(4);
                    receiveFile(filename, dis);
                } else if (command.equals("quit")) {
                    break;
                }
            }

            System.out.println("连接关闭: " + socket.getInetAddress());
            dis.close();
            dos.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//发送文件操纵
    private void sendFileList(DataOutputStream dos) throws IOException {
        File dir = new File("E:\\Java\\JavaExperimentOne");
        File[] files = dir.listFiles();
        dos.writeInt(files.length);
        for (File file : files) {
            dos.writeUTF(file.getName());
            dos.writeLong(file.length());
        }
    }
//发送文件
    private void sendFile(String filename, DataOutputStream dos) throws IOException {
        File file = new File("E:\\Java\\JavaExperimentOne\\" + filename);
        if (!file.exists()) {
            dos.writeLong(-1);
            return;
        }
        dos.writeLong(file.length());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = fis.read(buffer)) != -1) {
            dos.write(buffer, 0, bytesRead);
        }
        fis.close();
    }
//接收文件
    private void receiveFile(String filename, DataInputStream dis) throws IOException {
        File file = new File("E:\\Java\\JavaExperimentOne\\" + filename);
        FileOutputStream fos = new FileOutputStream(file);
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = dis.read(buffer)) != -1) {
            fos.write(buffer, 0, bytesRead);
        }
        fos.close();
    }
}
